<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>VSCode 前后端表单交互</title>
  <style>body{font-family:Arial;margin:30px}</style>
</head>
<body>

<h2>1. 浏览器原生提交（会跳转）</h2>
<form action="http://localhost:3000/user/get" method="GET">
  用户名：<input name="username" required> <br>
  密码：  <input name="password" type="password" required> <br>
  <button>GET 提交（跳转）</button>
</form>

<hr>

<form action="http://localhost:3000/user/post" method="POST">
  用户名：<input name="username" required> <br>
  密码：  <input name="password" type="password" required> <br>
  <button>POST 提交（跳转）</button>
</form>

<hr>

<h2>2. JS 拦截后不刷新页面</h2>
<form id="jsForm">
  用户名：<input name="username" required> <br>
  密码：  <input name="password" type="password" required> <br>
  <button type="submit">JS 发 POST（不跳转）</button>
</form>

<pre id="log"></pre>

<script>
document.getElementById('jsForm').addEventListener('submit', async (e) => {
  e.preventDefault();                       // 阻止默认跳转
  const body = new URLSearchParams(new FormData(e.target)); // 表单编码
  const res = await fetch('http://localhost:3000/user/post', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body
  });
  const txt = await res.text();
  document.getElementById('log').textContent = txt; // 把后端返回打印
});
</script>

</body>
</html>